Skip to content

fix(discovery): refuse DiscoveryComplete before any evidence returns - #7552

Merged
M4n5ter merged 3 commits into
mainfrom
fix/discovery-complete-needs-evidence
Dec 3, 2026
Merged

M4n5ter merged 3 commits into
mainfrom
fix/discovery-complete-needs-evidence

Conversation

@UncertaintyDeterminesYou4ndMe

@UncertaintyDeterminesYou4ndMe UncertaintyDeterminesYou4ndMe commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A Proactive discovery worker could call DiscoveryComplete in its first model step, before any other tool had returned. The check then ended without investigating, and the submitted note was stored as an investigation record.

Preparing DiscoveryComplete now fails while no investigation tool has returned anything in an earlier model attempt of the Run. A result from the same model response does not count, because the model has not seen it. A direct call counts when it succeeded or failed. In Code Mode a call made inside exec counts when it returned a result or an error; exec and wait themselves do not, so a script that fails before it calls a tool is not evidence. tool_search, AskUserQuestion, CompactContext and the todo tools do not count. The rule does not apply when the step's authorized tool catalog holds no other tool. The refusal tells the model to investigate first, inside exec when the tools are not offered as separate functions, and then call DiscoveryComplete alone in a later step. The DiscoveryComplete description states the same rule.

Observed

A daily check on a trial root, model GLM-5.3-Flash with Code Mode. From 11-29 to 12-02, all 8 scheduled checks ended in their first model step with DiscoveryComplete {"kind":"no_report","note":"placeholder"} (or a Chinese note meaning "placeholder: read memory and history first"). Five of them sent tool_search in the same step. Each time the model's reasoning said it would first call DiscoveryMemory with list. In Code Mode the model-facing tools are exec, wait, AskUserQuestion, DiscoveryComplete and tool_search; DiscoveryMemory is only reachable inside exec. On 11-28 the same model called exec with tools.DiscoveryMemory(...) and completed a full report.

One earlier check (11-27) shows that an error alone was not enough: the model sent DiscoveryComplete with empty arguments, got an input error, wrote "I called DiscoveryComplete prematurely", and then sent DiscoveryComplete with the placeholder note, which was accepted.

Implementation notes

The check is Owner::require_discovery_evidence in discovery.rs, called from PreparedTool::prepare with the step catalog. It reads the agent_tools and agent_cells projections through Store::run_tool_returned, because the RunView given to the driver holds only the current step.

Tests

The discovery driver tests now read the fixture file before completing. Where a test changes the model route, the model list, the credential or the workspace between the worker's first step and its completion, the read happens before that change. New tests cover Code Mode (refusal, a failing exec, a nested DiscoveryMemory call, a worker with no tools) and deferred tools under toolDiscovery.

AI use

Claude Code (Claude Opus 5.5) found the cause in a trial root, wrote the change and ran the tests. Claude Fable 5.2 advised on the rule, and Claude Sonnet 5.5 reviewed the diff. The author asked for the fix and did not review the diff line by line.

A discovery worker could submit DiscoveryComplete in its first model step,
before any other tool returned. GLM-5.3-Flash in Code Mode did this on every
scheduled check from 2026-11-29 to 2026-12-02: it meant to call
DiscoveryMemory, which is only reachable inside exec there, and sent
DiscoveryComplete with a "placeholder" note instead. The check ended with no
investigation and stored the placeholder as a record.

The driver now refuses DiscoveryComplete while no call to another tool has
returned a successful result in the Run, unless the step offers nothing else
to call. tool_search does not count. In Code Mode the refusal says that
DiscoveryMemory and the other tools run inside exec.

Generated-by: Claude Code
@github-actions github-actions Bot added the effort/M Under 500 readable lines label Dec 2, 2026

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

Thanks for tracking down the GLM-5.3-Flash Code Mode failure mode. Preventing zero-evidence DiscoveryComplete calls from persisting placeholder records makes sense as a guardrail, though there are a couple of correctness edge cases and design/test gaps worth addressing before merge:

1. [Blocking] investigable checks step_advertised (wire surface), causing false positives in Code Mode and false negatives under toolDiscovery: true

In plugins/agent/native/src/owner/driver.rs, investigable inspects self.step_advertised (the current step's advertised wire tools) against NOT_EVIDENCE = &["DiscoveryComplete", "tool_search"]. That breaks in both directions:

  • Code Mode blocks legitimate completion when no investigation tools remain: discovery_approves_grouped_aliases_and_rechecks_the_parent_ceiling verifies that a worker whose granted tools disappear under the parent Bot's ceiling (leaving only DiscoveryComplete) must still be able to complete. However, in Code Mode, CodeCells::cell_definitions_for (plugins/agent/tools/src/cell/session.rs) unconditionally advertises ["exec", "wait"] even when availability.all().nested() is empty. Because exec and wait are not in NOT_EVIDENCE, investigable stays true, refusing DiscoveryComplete and telling the model to use DiscoveryMemory inside exec even though no investigation tools exist. (Similarly, CompactContext and AskUserQuestion are control/interaction tools rather than investigation tools, yet are not excluded.)
  • Non-Code Mode with toolDiscovery: true (production default) bypasses the guard for deferred-only grants: Default installation sets toolDiscovery: true (products/maka/bundle/src/installation.ts), and visible_before_search (plugins/agent/tool-catalog/src/availability.rs) only eagerly exposes always_visible tools plus Shell/Read/AskUserQuestion/ProcessStop/ProcessInput. If a discovery task is scoped via DiscoveryToolSelection to only deferred tools (e.g., WebFetch, WebSearch, Recall*, SessionList, ScheduledTask, or mcp__*, without Read or DiscoveryMemory), Step 1's step_advertised is just {"DiscoveryComplete", "tool_search"}. Both match NOT_EVIDENCE, so investigable evaluates to false and a first-step DiscoveryComplete is accepted immediately.

Suggested fix: Determine whether the worker has investigation tools from the actual authorized step ToolCatalog (already obtained on the next line via catalog_for_tool, which includes deferred and nested tools without virtual exec/wait/tool_search), excluding non-evidence control tools (DiscoveryComplete, CompactContext, AskUserQuestion).

2. [Important] Store::run_tool_succeeded misses CellRecovered and can deadlock when all investigation tools return Failed

  • Restart recovery (CellRecovered): RunToolSucceeded (plugins/agent/state/src/store.rs) filters on json_extract(body,'$.accepted.outcome.kind')='succeeded'. If a Code Mode worker's exec finishes across a Host restart, recovery accepts it with AcceptedResult::CellRecovered { cell } ("cell_recovered"), not "succeeded". Note that plugins/agent/state/src/fold.rs already treats CellRecovered with CellStatus::Completed as successful completion; duplicating the success check in raw SQL misses this path and will refuse DiscoveryComplete after recovery. (Also, filtering AND pending=0 lets the query use the agent_tools_pending(run, pending, key) index.)
  • Investigation tools that return AcceptedResult::Failed: While Read and WebFetch wrap ordinary file/web errors inside ToolSuccess (Succeeded), MCP tools with isError: true (plugins/agent/mcp/src/result.rs) and Recall/DiscoveryMemory/Host errors record AcceptedResult::Failed. For a worker scoped to e.g. an MCP monitor, an isError: true response is itself the evidence to report, yet requiring strictly succeeded prevents it from ever calling DiscoveryComplete. (By contrast, an exec script runtime error / Interrupted should still not count as evidence.)

3. [Important — Design] Address the prompt/tool-description trigger directly and keep discovery policy out of generic NativeDriver::decide_tool

  • Preventing the first-step mistake upfront: From the observed runs, the model saw DiscoveryComplete and tool_search at top level in Code Mode while DiscoveryMemory lived inside exec, and DiscoveryComplete's description (plugins/agent/native/src/owner/discovery.rs) does not warn against calling it before investigating or as a placeholder (compare Bot::Sleep in plugins/agent/native/src/owner/bot.rs, which states its preconditions and refusal rule directly). Updating DiscoveryComplete's description (and avoiding wasted first-step rejections) addresses the trigger rather than relying solely on the error text.
  • Refusal message accuracy: In premature_completion(code_mode), hardcoding {MEMORY} and tools.<name>(input) is inaccurate when DiscoveryMemory is not granted to the worker or when Python Code Mode is active.
  • Layering: Bot::Sleep keeps its refusal logic inside bot.rs. Hardcoding super::discovery::COMPLETE, NOT_EVIDENCE, and a second lock on self.step_advertised (without re-checking cached_step == step) inside generic NativeDriver::decide_tool leaks discovery-specific policy into the generic driver. Moving this check to discovery's preparation path (or alongside PreparedTool::prepare, where catalog/access/owner are already in hand) keeps decide_tool clean.

4. [Important — Tests] No Code Mode or tool_discovery test coverage

Fixture::new in plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs sets codeMode: false and does not exercise tool_discovery: true, so the new if code_mode refusal branch and both edge cases in #1 are currently uncovered (while 13 unrelated tests were modified to prepend Read("discovery.txt")). Adding dedicated behavior tests for:

  1. Code Mode rejecting first-step DiscoveryComplete (with the Code Mode hint) and accepting it after exec,
  2. Code Mode with zero granted investigation tools still allowing DiscoveryComplete,
  3. tool_discovery: true with deferred-only investigation tools rejecting both first-step DiscoveryComplete and tool_search-only before a real tool succeeds,

would directly cover the target scenario and prevent regressions.

Follow-up (non-blocking)

In Code Mode under the Session profile, a background discovery worker still exposes AskUserQuestion and a top-level tool_search (solely for deferred DirectOnly CompactContext), which explains why 5 of the 8 observed runs sent tool_search trying to find DiscoveryMemory. Trimming unnecessary direct-only tools from discovery workers in a follow-up would further reduce confusion.

简体中文

感谢定位 GLM-5.3-Flash 在 Code Mode 下的这个实际问题。给 DiscoveryComplete 加一道防零取证直接交 placeholder 的护栏方向是对的,但对照源码看还有几个正确性边界、分层设计与测试覆盖问题建议在合并前处理掉:

1. [Blocking] investigable 用 step_advertised(当前步 wire 工具面)判断,在 Code Mode 和 toolDiscovery: true(生产默认)下双向误判

plugins/agent/native/src/owner/driver.rs 里用 self.step_advertised 排查 NOT_EVIDENCE = &["DiscoveryComplete", "tool_search"] 之外的工具,这会在两个真实路径下同时出错:

  • Code Mode 下无调查工具时把合法完成堵死:已有测试 discovery_approves_grouped_aliases_and_rechecks_the_parent_ceiling 明确覆盖了父 Bot 收紧工具上限后 worker 只剩 DiscoveryComplete、需要能直接结束的场景。但在 Code Mode 下,CodeCells::cell_definitions_for(plugins/agent/tools/src/cell/session.rs)即使 availability.all().nested() 为空也会无条件暴露 ["exec", "wait"]。由于 exec 和 wait 不在 NOT_EVIDENCE 里,investigable 恒为 true,会把合法的 DiscoveryComplete 拒掉,并且报错还误导模型去 exec 里调 DiscoveryMemory。(另外 CompactContext 和 AskUserQuestion 也不是调查工具,但同样未排除。)
  • 非 Code Mode + toolDiscovery: true(生产默认)下全 deferred 工具绕过防线:默认配置启用了 toolDiscovery: true(products/maka/bundle/src/installation.ts),而 visible_before_search(plugins/agent/tool-catalog/src/availability.rs)在首步只暴露 always_visible 以及 Shell/Read/AskUserQuestion/ProcessStop/ProcessInput。如果用户通过 DiscoveryToolSelection 只授予了 deferred 调查工具(如 WebFetch、WebSearch、Recall*、SessionList、ScheduledTask 或 mcp__*,不含 Read/DiscoveryMemory),首步 step_advertised 只有 {"DiscoveryComplete", "tool_search"},全部命中 NOT_EVIDENCE,investigable 误判为 false,首步直接调用 DiscoveryComplete 会被放行。

建议修复:不要从当前步 wire 工具面 step_advertised 反推,直接基于这一步实际授权的完整 ToolCatalog(紧接着下一行 catalog_for_tool 就已经拿到,包含全部 deferred 与 nested 工具,且不含虚拟的 exec/wait/tool_search)排除控制类工具(DiscoveryComplete、CompactContext、AskUserQuestion)来判断是否有可调查工具。

2. [Important] Store::run_tool_succeeded 漏掉 CellRecovered,且对全部工具返回 Failed 的调查场景过严

  • 重启恢复(CellRecovered)漏判:RunToolSucceeded(plugins/agent/state/src/store.rs)只匹配 json_extract(body,'$.accepted.outcome.kind')='succeeded'。如果 Code Mode worker 的 exec 在 Host 重启期间完成,恢复结算写入的 outcome 是 AcceptedResult::CellRecovered { cell }("cell_recovered"),不是 "succeeded"。plugins/agent/state/src/fold.rs 本身已经把 CellStatus::Completed 的 CellRecovered 视为成功完成;这里单独写 SQL 匹配漏掉了恢复路径,会导致恢复后合法调用 DiscoveryComplete 被拒。(另外 SQL 加上 AND pending=0 可以命中 agent_tools_pending(run, pending, key) 索引。)
  • 调查工具返回 AcceptedResult::Failed 被卡死:虽然 Read/WebFetch 的常规业务错误会包在 ToolSuccess 里落为 Succeeded,但 MCP 工具返回 isError: true(plugins/agent/mcp/src/result.rs)以及 Recall/DiscoveryMemory/Host 失败都会记录为 AcceptedResult::Failed。如果某个监控任务仅授权了 MCP 工具,目标服务报错本身就是调查结论,纯按 succeeded 卡死会导致永远无法提交结果。(不过 Code Mode 下 exec 脚本自身的运行时异常 Interrupted 确实不应算有效取证。)

3. [Important — 设计] 建议同步修掉工具描述诱因,并把 Discovery 领域策略收口出通用 NativeDriver::decide_tool

  • 从源头减少首步误调:从 Observed 日志看,模型在 Code Mode 顶层看到 DiscoveryComplete 和 tool_search,而 DiscoveryMemory 藏在 exec 内;同时 DiscoveryComplete 的工具描述(plugins/agent/native/src/owner/discovery.rs)完全没说明“必须先调查再单独调用、禁止首步占位”(对比同为 FinishTurn 的 Bot::Sleep,plugins/agent/native/src/owner/bot.rs 里直接把调用前提和拒绝条件写进了描述)。把描述补清楚可以避免每次都先浪费一轮失败调用再靠拒绝报错纠偏。
  • 拒绝提示准确性:premature_completion(code_mode) 写死了 {MEMORY} 和 JS 语法 tools.<name>(input),在未授权 DiscoveryMemory 或 Python Code Mode 下不准确。
  • 分层归属:Bot::Sleep 的拒绝逻辑收口在 bot.rs 自身;这里把 super::discovery::COMPLETE、NOT_EVIDENCE 以及对 self.step_advertised 的二次加锁(且未重验 cached_step == step)直接写进通用 NativeDriver::decide_tool,让通用层承担了 Discovery 领域规则。建议收口到 discovery 自己的 prepare 边界(或已经拿到 catalog/access/owner 的 PreparedTool::prepare 路径)。

4. [Important — 测试] 缺少 Code Mode 和 tool_discovery 覆盖

plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs 里 Fixture::new 固定为 codeMode: false,也没有开启 tool_discovery: true 的用例,导致新增的 if code_mode 分支和第 1 点中的两个问题都没被测试覆盖(同时 13 个不相关用例都被迫加了一步 Read("discovery.txt"))。建议补充独立的行为测试直接覆盖:

  1. Code Mode 下首步 DiscoveryComplete 被拒并带正确提示,随后通过 exec 调查后放行;
  2. Code Mode 下无调查工具授权时仍允许直接 DiscoveryComplete;
  3. tool_discovery: true 且仅授权 deferred 工具时,首步 DiscoveryComplete 和仅调用 tool_search 后均被拒,实际工具返回后再放行。

Follow-up(非本 PR 阻断项)

Session profile 下后台运行的 Discovery worker 在 Code Mode 顶层仍带着 AskUserQuestion 以及仅服务 CompactContext 的 tool_search(这次 8 次失败里有 5 次因此发了 tool_search 去找 DiscoveryMemory)。后续清理 discovery worker 的顶层 DirectOnly 工具面能进一步减少模型误判。

…alls

Move the check into the discovery preparation path. A worker is exempt
only when its step catalog holds no investigation tool. Count direct
calls that succeeded or failed, and nested calls inside code cells that
returned, but not exec, wait or tool_search themselves. State the rule in
the DiscoveryComplete description and drop mode-specific refusal text.

Generated-by: Claude Code
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All four points were valid. The new head changes the check as follows.

1. Which workers are checked. The check now reads the step's authorized ToolCatalog, not step_advertised. A worker is exempt when its catalog holds nothing except DiscoveryComplete, CompactContext, AskUserQuestion, tool_search, exec, wait, todo_read and todo_write. So a Code Mode worker with no granted tools can complete at once, and deferred tools under toolDiscovery count as investigation tools.

2. What counts as evidence. Store::run_tool_returned (was run_tool_succeeded) accepts:

  • a direct call outside that list with outcome succeeded or failed (pending=0);
  • a nested call inside a code cell of the Run that returned a result or an error (CellChild::returned, which ignores rejected calls).

exec and wait themselves do not count. An exec that throws without calling a tool is not evidence. A nested call recorded in the cell is evidence however the exec call was later accepted, including cell_recovered.

3. Layering and wording.

  • The check is Owner::require_discovery_evidence in discovery.rs, called from PreparedTool::prepare next to the existing CompactContext and Shell cases. decide_tool is back to its main-branch form.
  • The DiscoveryComplete description now says it is not a first step or a placeholder, and that it should be called alone after the other tools return.
  • The refusal no longer names DiscoveryMemory or a script syntax. It says to use the other tools first, inside exec when they are not offered as separate functions.

4. Tests. Two new tests:

  • discovery_code_mode_completion_needs_a_tool_result_inside_exec: a first-step completion is refused, an exec that throws is not enough, tools.Read(...) inside exec is enough, and a Code Mode worker with no selected tools completes at once.
  • discovery_completion_with_deferred_tools_needs_more_than_tool_search: with toolDiscovery on and only a deferred tool selected, completion is refused at the first step and again after tool_search, and accepted after that tool returns.

The fixture worker has Read, so a first-step completion in the existing tests is now refused by design. That is why those tests read the fixture file first.

The follow-up about trimming direct-only tools from discovery workers is not in this PR.

Posted by Claude Opus 5.5 (AI).

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

LGTM — all four points from the previous review are cleanly addressed, and checking CellChild::returned() on agent_cells is even cleaner than relying on exec outcomes (it also blocks empty/no-op exec scripts and handles CellRecovered naturally). Feel free to merge as-is.

One small non-blocking note in case you want to tighten it now or in a follow-up:

  • Same-attempt streaming interleaving: Store::run_tool_returned currently scans all agent_tools and agent_cells rows for the run without excluding the current attempt. On adapters with supports_item_acceptance() == true (OpenAI Responses API / Codex), if a model emits [Read/exec, DiscoveryComplete(placeholder)] in Step 1, the first tool call can execute and settle before the streamed DiscoveryComplete call arrives in the same attempt (and similarly under Code Mode where direct_tool_batching() == false, or across a Host restart between deciding sibling calls). Excluding the current attempt (available via ToolOrigin::Provider { link } -> link.attempt in context.call.origin) with json_extract(body,'$.key.attempt') <> ?3 on agent_tools and owner_attempt IS DISTINCT FROM ?2 on agent_cells would strictly enforce the "in a later step" contract with a few lines.

No blocker at all — ready to merge whenever you like.

简体中文

LGTM——上一轮提到的四个问题都已经收口得很干净,通过 agent_cells 上的 CellChild::returned() 判定比依赖 exec 自身状态更简洁(顺手连空跑的 exec 脚本也拦住了,并且天然覆盖 CellRecovered)。可以随时合并。

顺手留一个小问题(非阻塞,想现在补或留作后续都可以):

  • 同一 attempt 流式交错边界:Store::run_tool_returned 目前会扫描整场 run 的所有 agent_tools 和 agent_cells,没有排除当前 attempt。在开启 supports_item_acceptance() == true 的适配器(OpenAI Responses API / Codex)上,如果模型首步同一次响应连发 [Read/exec, DiscoveryComplete(placeholder)],第一个工具可能在流式生成完第二个 DiscoveryComplete 之前就已经执行结算(Code Mode 下 direct_tool_batching() == false 或同一步两个调用之间恰好发生 Host 重启恢复时也有类似路径),导致模型还没见过结果就被放行。从 context.call.origin 的 ToolOrigin::Provider { link } 取出当前 link.attempt,在 agent_tools 加 json_extract(body,'$.key.attempt') <> ?3、在 agent_cells 加 owner_attempt IS DISTINCT FROM ?2 即可用几行代码把“必须后续 step 调用”的约束彻底闭环。

不阻断合并,作者觉得合适随时合就行。

A tool that settles while the same streamed response is still producing
DiscoveryComplete has a result the model has not seen. Only results from
earlier model attempts now count as evidence.

Generated-by: Claude Code
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Thanks. I took the same-attempt note in 6791c2c: Store::run_tool_returned now takes the current attempt from ToolOrigin::Provider { link } and skips agent_tools rows whose key.attempt matches it and agent_cells rows whose owner_attempt matches it. The refusal text now says "returned anything to you".

I tried to cover it with a test that sends exec and DiscoveryComplete in one mock response. That test also passed without the change, because in the mock path DiscoveryComplete is prepared before the exec cell settles, so I did not keep it. The existing 28 discovery tests pass.

Posted by Claude Opus 5.5 (AI).

@M4n5ter
M4n5ter merged commit 7c2e3fc into main Dec 3, 2026
1 check passed
@M4n5ter
M4n5ter deleted the fix/discovery-complete-needs-evidence branch December 3, 2026 06:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/M Under 500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants